package com.alogic.nginx.xscript;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.BaseException;
import com.anysoft.util.IOTools;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.io.File;
import java.io.FileOutputStream;

/**
 * 保存为文件
 * @author yyduan
 * @since 1.6.12.25 [20190311 duanyy] <br>
 */
public class NginxSave extends AbstractLogiclet {
	
	/**
	 * 上下文id
	 */
	protected String pid = "$nginx-conf";

	protected String $path = "";
	
	protected String encoding = "utf-8";
	
	public NginxSave(String tag, Logiclet p) {
		super(tag, p);
	}

	@Override
	public void configure(Properties p){
		super.configure(p);
		
		pid = PropertiesConstants.getString(p, "pid", pid,true);
		$path = PropertiesConstants.getRaw(p,"path",$path);
		encoding = PropertiesConstants.getString(p,"encoding",encoding,true);
	}
	
	@Override
	protected void onExecute(XsObject root, XsObject current, final LogicletContext ctx, final ExecuteWatcher watcher){
		StringBuffer content = ctx.getObject(pid);
		if (content == null){
			throw new BaseException("core.e1001","It must be in a ngx-conf context,check your script.");
		}

		String path = PropertiesConstants.transform(ctx,$path,"");
		
		if (StringUtils.isNotEmpty(path)){
			File file = new File(path);
			if (!file.exists()){				
				FileOutputStream out = null;
				try {
					out = new FileOutputStream(file);
					out.write(content.toString().getBytes(encoding));
				}catch (Exception ex){
					log(ExceptionUtils.getStackTrace(ex),"error");
				}finally{
					IOTools.close(out);
				}
			}
		}else{
			log(content.toString(),"info");
		}
	}

	protected static String getIndent(int indent){
		return indent > 0 ? String.format(String.format("%%%ds", indent), "\t") : "";
	}
}
